package com.wwj.app.v1;

import com.wwj.core.pay.bbn.BBNPaySDKConfig;
import com.wwj.core.pay.bbn.service.IBBNPayService;
import com.wwj.core.pay.weixin.refund.MD5Util;
import com.wwj.core.wawa.service.IPlayerRechargeService;
import com.wwj.framework.controller.BaseController;
import com.wwj.framework.utils.ReturnData;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TreeMap;

@Controller
@RequestMapping("/v1/pay")
public class H5PayController extends BaseController {

    @Resource
    private IPlayerRechargeService playerRechargeService;

    @Resource
    private IBBNPayService bbnPayService;

    @RequestMapping("/bbn/notify")
    public void bbnPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String respText = "SUCCESS";

        String transdata = request.getParameter("transdata");
        String sign = request.getParameter("sign");
        String signtype = request.getParameter("signtype");

        if(transdata == null || "".equals(transdata) || sign == null || "".equals(sign) || signtype==null || !"MD5".equals(signtype)) {
            logger.error("BBNPAY NOTIFY : PARA IS ERROR");
            respText = "FAILURE";
        } else {
            transdata = decode(transdata, "utf-8");
            // 解析返回结果
            JSONObject payResult = JSONObject.fromObject(transdata);
            if(payResult == null) {
                logger.error("BBNPAY NOTIFY : PAYRESULT IS ERROR");
                respText = "FAILURE";
            } else {
                Integer result = payResult.getInt("result");
                String transid = payResult.getString("transid");
                String paytype = payResult.getString("paytype");
                String order_no = payResult.getString("cporderid");
                String player_id = payResult.getString("pcuserid");

                // 验证支付结果
                TreeMap<String, Object> paraMap = new TreeMap<String, Object>();
                paraMap.put("transtype", payResult.getInt("transtype"));
                paraMap.put("cporderid", payResult.getString("cporderid"));
                paraMap.put("transid", payResult.getString("transid"));
                paraMap.put("pcuserid", payResult.getString("pcuserid"));
                paraMap.put("appid", payResult.getString("appid"));
                paraMap.put("goodsid", payResult.getString("goodsid"));
                paraMap.put("feetype", payResult.getInt("feetype"));
                paraMap.put("money", payResult.getInt("money"));
                paraMap.put("fact_money", payResult.getInt("fact_money"));
                paraMap.put("currency", payResult.getString("currency"));
                paraMap.put("result", payResult.getInt("result"));
                paraMap.put("transtime", payResult.getString("transtime"));
                paraMap.put("pc_priv_info", payResult.getString("pc_priv_info"));
                paraMap.put("paytype", payResult.getString("paytype"));

                // 生成MD5值
                String payUrlStr = bbnPayService.generateParamsStrInOrder(paraMap);
                payUrlStr += "key=" + BBNPaySDKConfig.APP_KEY;
                String payParaMd5 = MD5Util.MD5Encode(payUrlStr, "utf-8");

                if(!sign.equals(payParaMd5)) {
                    logger.error("BBNPAY NOTIFY : SIGN IS ERROR");
                    respText = "FAILURE";
                } else {
                    boolean deal;
                    if (result != null
                            && result == 1
                            && !"".equals(transid)
                            && !"".equals(paytype)
                            && !"".equals(order_no)
                            && !"".equals(player_id)) { // 交易成功
                        deal = playerRechargeService.dealRechargeComplete(Integer.valueOf(player_id), order_no, true, result);
                    } else { // 交易失败
                        deal = playerRechargeService.dealRechargeComplete(Integer.valueOf(player_id), order_no, false, result);
                    }
                    if(!deal) {
                        respText = "FAILURE";
                    }
                }
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(respText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    @RequestMapping("/recharge")
    @ResponseBody
    public ReturnData recharge(@RequestParam Integer playerId, @RequestParam Integer itemId, @RequestParam int payType,
                               @RequestParam(required = false) Integer couponId) {
        ReturnData returnData = new ReturnData();
        try {
            String payUrl = playerRechargeService.dealPlayerRechargeByBBN(playerId, itemId, payType, couponId);
            if(payUrl == null) {
                returnData.failure("无法支付，联系客服");
                return returnData;
            }

            returnData.success(payUrl);
        } catch (Exception e) {
            logger.error("", e);
            returnData.failure("系统错误,请联系客服");
        }
        return returnData;
    }

    @RequestMapping("/forward")
    public ModelAndView forward(@RequestParam String url) {
        ModelAndView modelAndView = new ModelAndView("bbn_redirect");
        url = new String(Base64.decodeBase64(url));
        modelAndView.addObject("redirectUrl", url);
        return modelAndView;
    }

    @RequestMapping("/complete")
    public ModelAndView complete() {
        ModelAndView modelAndView = new ModelAndView("bbn_pay_complete");
        return modelAndView;
    }

    @RequestMapping("/freight")
    @ResponseBody
    public ReturnData freight(@RequestParam Integer playerId, @RequestParam int payType) {
        ReturnData returnData = new ReturnData();
        try {
            String payUrl = playerRechargeService.dealPlayerRechargeByBBN(playerId, -1, payType, -1);
            if(payUrl == null) {
                returnData.failure("无法支付，联系客服");
                return returnData;
            }

            returnData.success(payUrl);
        } catch (Exception e) {
            logger.error("", e);
            returnData.failure("系统错误,请联系客服");
        }
        return returnData;
    }
}
